﻿using System;
using System.Collections.Generic;
using System.Linq;
using HiStaff.Base;
using HiStaff.Control;
using HiStaff.Domain.IN;
using HiStaff.Domain.Sys;
using HiStaff.Util;
using HiStaff.Dal;
using Janus.Windows.GridEX;
using System.Data;

namespace HiStaff.iInsurance
{
    public partial class OrganizationInsCenter : FormBase
    {
        private List<LST_ORG_INS> lstOrgIns;
        public OrganizationInsCenter()
        {
            InitializeComponent();
        }
        protected override bool FormLoad()
        {
            base.CreateCommandBar(CommandBarManager.ActionCommand.Edit,
                CommandBarManager.ActionCommand.Separator,
                CommandBarManager.ActionCommand.Save,
                CommandBarManager.ActionCommand.Cancel,
                CommandBarManager.ActionCommand.Separator,
                CommandBarManager.ActionCommand.Exit,
                CommandBarManager.ActionCommand.Separator);
            
            InitGrid();
            BindData();
            base.CreateDropdownInCommandBar("OPTCHECK", "Option check node", 150, 2);
            var lstCheck = new List<SY_DEFAULT_LIST>();
            lstCheck.Add(new SY_DEFAULT_LIST { ID = 1m, NAME = "One node" });
            lstCheck.Add(new SY_DEFAULT_LIST { ID = 2m, NAME = "One and with Childs node" });
            base.SetDataSourceToDropdownCommand("OPTCHECK", lstCheck, "NAME", "ID", true);
            base.GetCommandByKey("OPTCHECK").GetUIComboBox().SelectedIndex = 0;
            SetToolStripButtonBar(CommandBarManager.ActionCommand.Cancel);
            return base.FormLoad();
        }
        private void InitGrid()
        {
            GridEXColumn col;

            grdData.RootTable.HierarchicalMode = HierarchicalMode.SelfReferencing;
            grdData.RootTable.SelfReferencingSettings.ChildDataMember = "PARENTID";
            grdData.RootTable.SelfReferencingSettings.ParentDataMember = "ID";
            grdData.RootTable.SelfReferencingSettings.ParentRootMode = ParentRootMode.NullValue;
            grdData.RootTable.SelfReferencingSettings.TreatOrphanRowsAsRoot = true;
            grdData.RootTable.SelfReferencingSettings.AggregationMode = SelfReferencingAggregationMode.RootRows;
            grdData.FrozenColumns = 3;

            col = new GridEXColumn();
            col.Key = "ID";
            col.DataMember = "ID";
            col.Caption = "ID";
            col.ColumnType = ColumnType.Text;
            col.EditType = EditType.NoEdit;
            col.HeaderAlignment = TextAlignment.Center;
            col.Visible = false;
            grdData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = "PARENTID";
            col.DataMember = "PARENTID";
            col.Caption = "PARENTID";
            col.ColumnType = ColumnType.Text;
            col.EditType = EditType.NoEdit;
            col.HeaderAlignment = TextAlignment.Center;
            col.Visible = false;
            grdData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = "NAME";
            col.DataMember = "NAME";
            col.Caption = "TÊN PHÒNG BAN";
            col.ColumnType = ColumnType.Text;
            col.EditType = EditType.NoEdit;
            col.FilterEditType = FilterEditType.TextBox;
            col.HeaderAlignment = TextAlignment.Center;
            col.Width = 300;
            grdData.RootTable.Columns.Add(col);
            grdData.RootTable.SelfReferencingSettings.ExpandColumn = col;

            lstOrgIns = OracleHelper.ExcuteSelectMultiObject<LST_ORG_INS>("APRS_LST_ORG_INS", new LST_ORG_INS { STATUS = 1 });

            foreach (var item in lstOrgIns)
            {
                col = new GridEXColumn();
                col.Key = string.Format("A{0}", item.ID);
                col.DataMember = string.Format("A{0}", item.ID);
                col.Caption = item.CODE;
                col.HeaderStyle.TextAlignment = TextAlignment.Center;
                col.ColumnType = ColumnType.CheckBox;
                col.EditType = EditType.CheckBox;
                col.FilterEditType = FilterEditType.SameAsEditType;
                col.CheckBoxFalseValue = 0m;
                col.CheckBoxTrueValue = 1m;
                col.CheckBoxTriState = false;
                col.Width = 80;
                col.HeaderToolTip = item.CODE + " - " + item.NAME;
                col.CellToolTipText = item.CODE + " - " + item.NAME;
                grdData.RootTable.Columns.Add(col);
            }
        }
        private void BindData()
        {
            grdData.DataSource = OracleHelper.ExcuteSelectDataTable("PRS_SY_INSCENTER_ORG", new IN_ORG_INSCENTER());
            grdData.Refresh();
        }
        protected override void SetToolStripButtonBar(CommandBarManager.ActionCommand cmd)
        {
            switch (cmd)
            {
                case CommandBarManager.ActionCommand.Edit:
                    SetEnabledCommandSave = true;
                    SetEnabledCommandCancel = true;
                    SetEnabledCommandEdit = false;
                    base.GetCommandByKey("OPTCHECK").Enabled = Janus.Windows.UI.InheritableBoolean.True;
                    break;
                case CommandBarManager.ActionCommand.Cancel:
                case CommandBarManager.ActionCommand.Save:
                    SetEnabledCommandSave = false;
                    SetEnabledCommandCancel = false;
                    SetEnabledCommandEdit = true;
                    base.GetCommandByKey("OPTCHECK").Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    break;
            }
        }
        protected override bool EditButtonClick()
        {
            grdData.AllowEdit = InheritableBoolean.True;
            return true;
        }
        protected override bool CancelButtonClick()
        {
            grdData.AllowEdit = InheritableBoolean.False;
            BindData();
            return true;
        }
        protected override bool SaveButtonClick()
        {
            ExcuteAsynchronous();
            grdData.AllowEdit = InheritableBoolean.False;
            return true;
        }
        protected override bool AsynchronousFunctionWithBGW(System.ComponentModel.BackgroundWorker bgWorker)
        {
            DataTable dt = (DataTable)grdData.DataSource;
            int i = dt.Rows.Count + 1;
            int j = 0;
            int percent;
            decimal? orgId;
            foreach (DataRow drow in dt.Rows)
            {
                j++;
                orgId = ConvertHelper.ToDecimal(drow["ID"]);
                if (orgId.HasValue)
                {
                    OracleHelper.ExcuteNonQuery("APRD_IN_ORG_INSCENTER", new IN_ORG_INSCENTER
                    {
                        ORG_ID = orgId
                    });
                    foreach (DataColumn col in drow.Table.Columns)
                    {
                        if (drow[col.ColumnName].Equals(1m) && ConvertHelper.ToDecimal(col.ColumnName.Replace("A","")).HasValue)
                        {
                            OracleHelper.ExcuteNonQuery("APRU_IN_ORG_INSCENTER", new IN_ORG_INSCENTER
                            {
                                ORG_ID = orgId,
                                CENTER_ID = ConvertHelper.ToDecimal(col.ColumnName.Replace("A", ""))
                            });
                        }
                    }
                }
                percent = (j * 100 / i);
                bgWorker.ReportProgress(percent, "Đang thực hiện");
            }
            bgWorker.ReportProgress(100, "Hoàn tất");
            return true;
        }
        private void ChangeValue(string key, object curOrgId, object curValue)
        {
            var dtValue = (DataTable)grdData.DataSource;
            foreach (DataRow item in dtValue.Rows)
            {
                if (item["PARENTID"].Equals(curOrgId))
                {
                    item[key] = curValue;
                    if (curValue.Equals(1m))
                    {
                        foreach (var a in lstOrgIns)
                        {
                            if (string.Format("A{0}", a.ID) != key)
                                item[string.Format("A{0}", a.ID)] = 0;
                        }
                    }
                    ChangeValue(key, item["ID"], curValue);
                }
            }
        }
        private void grdData_CellEdited(object sender, ColumnActionEventArgs e)
        {

            object curOrgId = grdData.CurrentRow.Cells["ID"].Value;
            object curValue = grdData.CurrentRow.Cells[e.Column.Key].Value;
            if (curValue.Equals(1m))
            {
                foreach (var a in lstOrgIns)
                {
                    if (string.Format("A{0}", a.ID) != e.Column.Key)
                        grdData.CurrentRow.Cells[string.Format("A{0}", a.ID)].Value = 0;
                }
            }
            if (ConvertHelper.ToDecimal(base.GetCommandByKey("OPTCHECK").GetUIComboBox().SelectedValue) == 2m)
            {
                ChangeValue(e.Column.Key, curOrgId, curValue);
            }
        }

        private void grdData_CellValueChanged(object sender, ColumnActionEventArgs e)
        {
            grdData.Col -= 1;
            grdData.Col += 1;
        }
    }
}
